<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="deptFormInfo.ref"
            :data="deptFormInfo.data"
            :field-list="deptFormInfo.fieldList"
            :label-width="deptFormInfo.labelWidth"
          >
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <div class="layui-card-body fullBox table-height">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :api="getDeptProductAll"
                  :pager="false"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :tab-index="true"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-licenseNumber="scope">
                    <p>{{ scope.row.licenseNumber }}</p>
                    <p>{{ scope.row.brandName }}</p>
                  </template>
                  <template v-slot:col-commonName="scope">
                    <p>{{ scope.row.commonName }}</p>
                    <p>{{ scope.row.productCode }}</p>
                    <p>{{ scope.row.alias }}</p>
                  </template>
                  <template v-slot:col-type="scope">
                    <p>{{ scope.row.productTypeValue }}</p>
                    <p>{{ scope.row.codeTypeValue }}</p>
                    <p>{{ scope.row.productCategoryValue }}</p>
                  </template>
                  <template v-slot:col-standard="scope">
                    <p>{{ scope.row.standard }}</p>
                    <p>{{ scope.row.unitName }}</p>
                  </template>
                </page-table>
              </el-form>
            </div>
            <select-product
              v-if="productInfo.visible"
              @callback="_selectProduct"
              v-model:showDialog="productInfo.visible"
              :query="productInfo.query"
            />
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="deptProductDetailManage">
import {
  getDeptProductAll,
  delDeptProduct,
  updateDeptProduct,
  productsDepotExportExcel
} from '@/api/core'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'tableRow'])

// 过滤相关配置
const filterInfo = ref({
  query: {
    deptId: props.tableRow.id,
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '证号\n生产厂家', value: 'licenseNumber', type: 'slot' },
    { label: '通用名称\n编码\n别名', value: 'commonName', type: 'slot' },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [{ label: '删除产品', event: removeProduct, show: true }],
  },
})
// 表单相关
const deptFormInfo = ref({
  ref: null,
  data: {
    ...props.tableRow,
  },
  fieldList: [
    { label: '部门名称', value: 'name', type: 'input', disabled: true },
    {
      label: '允许使用所有产品',
      value: 'ownAllProduct',
      type: 'select-model',
      code: 'yes_or_no',
      labelTip:
        '是：允许使用产品库中所有启用状态的产品，否：只允许使用下列明细表中添加的启用状态产品',
    },
  ],
  labelWidth: '160px',
})
const selectRows = ref([])
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }, {label: '导出excel', event: exportExcel, show: proxy.$permission('dept:exportExcel')}],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  query: {
    idNotIn: '',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canRemoveProduct = computed(() => {
  return selectRows.value.length != 0
})

onMounted(() => {
  proxy.$nextTick(() => {
    getList()
  })
})
function exportExcel() {
  productsDepotExportExcel(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function deleteCheck() {
  if (selectRows.value && selectRows.value.length != 0) {
    let data = []
    selectRows.value.forEach((item) => {
      if (item) {
        data.push(item.id)
      }
    })
    deleteHandle(data)
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请至少选择一条操作数据',
    })
  }
}
function removeProduct(row) {
  if (row) {
    tableInfo.value.data = tableInfo.value.data.filter((value) => value !== row)
  } else {
    tableInfo.value.data = tableInfo.value.data.filter(
      (value) => !selectRows.value.includes(value)
    )
  }
}
function deleteHandle(data) {
  proxy.$handleAPI('delete', delDeptProduct, data).then((res) => {
    if (res.success) {
      tableInfo.value.initCurpage = Math.random()
      tableInfo.value.refresh = Math.random()
      selectRows.value = []
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      selectRows.value = data
      filterInfo.value.list[1].disabled = !selectRows.value.length
      break
  }
}
function save() {
  deptFormInfo.value.ref.validate((valid) => {
    if (valid) {
      saveDetail()
    }
  })
}
function saveDetail() {
  let data = {
    coreDept: deptFormInfo.value.data,
    coreDeptProducts: [],
  }

  data.coreDeptProducts = tableInfo.value.data.map((item) => {
    return {
      deptId: props.tableRow.id,
      productId: item.productId,
    }
  })
  updateDeptProduct(data).then((resp) => {
    if (resp && resp.success) {
      showDialog.value = false
      emits('returnModify', false)
    }
  })
}
function addProduct() {
  productInfo.value.query.idNotIn = tableInfo.value.data
    .map(function (item) {
      return item.productId
    })
    .toString()
  productInfo.value.visible = true
}
function _selectProduct(rows) {
  if (rows) {
    let newData = []
    rows.map((item) => {
      newData.push({
        ...item,
        id: null,
        productId: item.id,
        productCode: item.code,
        productType: item.type,
      })
    })
    tableInfo.value.data.push(...newData)
  }
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow-y: hidden;
}
</style>
